// 打开或者创建一个IndexedDB数据库
let openRequest = indexedDB.open("MyTestDatabase",1);
 
// 数据库版本变更的回调
openRequest.onupgradeneeded = function(e) {
    // 创建一个对象存储空间（OSpace），并指定一个自增主键
    let db = e.target.result;
    let store = db.createObjectStore("MyTestTable", { keyPath: "id", autoIncrement:true });
    store.createIndex("NameIndex", "name", { unique: false });
    store.createIndex("EmailIndex", "email", { unique: true });
}
 
// 数据库打开成功的回调
openRequest.onsuccess = function(e) {
    // 数据库操作成功，获取数据库实例
    let db = e.target.result;
    console.log("Database opened successfully");
}
 
// 数据库打开失败的回调
openRequest.onerror = function(e) {
    console.log("Database opened failed");
}
 
// 创建或者打开一个事务
let transaction = db.transaction(["MyTestTable"], "readwrite");
 
// 获取操作指定表的对象存储空间
let objectStore = transaction.objectStore("MyTestTable");
 
// 添加数据
let addRequest = objectStore.add({ id: 1, name: "John Doe", email: "john@example.com" });
addRequest.onsuccess = function(e) {
    console.log("Data added successfully");
};
 
// 读取数据
let getRequest = objectStore.get(1);
getRequest.onsuccess = function(e) {
    console.log("Data read successfully: ", e.target.result);
};
 
// 更新数据
let updateRequest = objectStore.put({ id: 1, name: "John Doe", email: "john_doe@example.com" });
updateRequest.onsuccess = function(e) {
    console.log("Data updated successfully");
};
 
// 删除数据
let deleteRequest = objectStore.delete(1);
deleteRequest.onsuccess = function(e) {
    console.log("Data deleted successfully");
};